/**
 * web2010_admin
 * com.xsoft.web.interceptor AdminInterceptor.java
 */
package com.xsoft.web.interceptor;

import java.util.ArrayList;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.xsoft.logic.model.sys.User;
import com.xsoft.logic.model.sys.UserRolePrivilege;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @author 潘冬 2010-8-19 下午05:02:36
 */
public class AdminInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		
		System.out.println("Action Class:"+ arg0.getAction().getClass().getSimpleName());
		System.out.println("Invocation Context:"+ arg0.getInvocationContext().getName());
		
		HttpServletResponse response = (HttpServletResponse)arg0.getInvocationContext().get(ServletActionContext.HTTP_RESPONSE);
		
		Map session = arg0.getInvocationContext().getSession();
		if (session.get("user") == null) {
			session.clear();
			response.sendRedirect("http://localhost:8086/commonSys/manager/error.jsp?type=1");
			return null;
//			return "login"; //这里尽量不要这样些，因为他是服务器内部的调整。url并不改变的。
		}
		User user = (User) session.get("user");
		ArrayList<UserRolePrivilege> privilegeList = (ArrayList<UserRolePrivilege>) session.get("privilegeList");
		Object action = arg0.getAction();
		
		String namespace = arg0.getProxy().getNamespace();
		if(namespace!=null && (namespace.trim().length()>0)){
			if("/".equals(namespace.trim())){
			}else{
				namespace +="/";
			}
		}
		String URL = "/commonSys"+namespace+arg0.getProxy().getActionName();
		
		if (action instanceof UserAware) {
			((UserAware) action).setUser(user);
			if (!"1".equals(user.getIsRoot())) {
				if (privilegeList == null || privilegeList.size() == 0) {
					session.clear();
					response.sendRedirect("http://localhost:8086/commonSys/manager/error.jsp");
					return null;
				}
				
				for(int i=0;i<privilegeList.size();i++){
					if(privilegeList.get(i).getMenu().getUrl().indexOf(URL)>-1){
						break;
					}
					if(i==privilegeList.size()-1){
						session.clear();
						response.sendRedirect("http://localhost:8086/commonSys/manager/error.jsp");
						return null;
					}
				}
//				((UserAware) action).setUserLimits(userLimits);
			}
		}
		return arg0.invoke();
	}

}
